import React, { useState, useEffect } from 'react';
import { Input, Button, Table, Pagination, Modal } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { searchUser, getAdminListLength, returnListData, changeIdentityToUser } from '@/api/userInfo/index';
import CreateAdminDialog from './components/createAdmin'
import EditAdminDialog from './components/editAdmin'
import { tracking } from '@/core/utils/operation'

const AdminPage = () => {
  const [adminAccount, setAdminAccount] = useState();
  const [tableData, setTableData] = useState([]);
  const [paginationData, setPaginationData] = useState({
    pageCount: 1,
    currentPage: 1,
  });
  const [adminTotal, setAdminTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [adminId, setAdminId] = useState();
  const name = JSON.parse(localStorage.getItem('userInfo')).name

  const fetchFirstPageList = async () => {
    setLoading(true);
    const data = await returnListData(1, '消息管理员');
    setTableData(data);
    setLoading(false);
  };

  useEffect(() => {
    const fetchAdminListLength = async () => {
      const res = await getAdminListLength('消息管理员');
      setAdminTotal(res.length);
      setPaginationData(prev => ({
        ...prev,
        pageCount: Math.ceil(res.length / 10),
      }));
    };

    fetchAdminListLength();
  }, []);

  useEffect(() => {
    fetchFirstPageList();
  }, []);

  const searchAdmin = async () => {
    try {
      setLoading(true);
      if (!adminAccount) {
        const data = await returnListData(paginationData.currentPage, '消息管理员');
        setTableData(data);
      } else {
        const data = await searchUser(adminAccount, '消息管理员');
        setTableData(data);
      }
      setPaginationData(prev => ({
        ...prev,
        pageCount: 1,
      }));
      setLoading(false);
    } catch (error) {
      console.error('Error searching admin:', error);
    }
  };

  const handleEditAdmin = (record) => {
    setAdminId(record.id)
    setEditModalVisible(true);
  }

  const handleDeleteAdmin = (record) => {
    try {
      Modal.confirm({
        title: '确定删除该管理员吗？',
        content: '删除后将无法恢复，请谨慎操作。',
        onOk: async () => {
          await changeIdentityToUser(record.id)
          await tracking('管理员', name, record.name, '高级')
          fetchFirstPageList();
        },
        onCancel() { },
      });
    } catch (error) {
      console.error('Error deleting admin:', error);
    }
  };

  const handlePaginationChange = async (page) => {
    setPaginationData(prev => ({
      ...prev,
      currentPage: page,
    }));
    setLoading(true);
    const data = await returnListData(page, '消息管理员');
    setTableData(data);
    setLoading(false);
  };

  const clearInput = async () => {
    setAdminAccount(undefined);
    setLoading(true);
    const data = await returnListData(paginationData.currentPage, '消息管理员');
    setTableData(data);
    setLoading(false);
  };

  const columns = [
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '更新时间',
      dataIndex: 'updateAt',
      key: 'updateAt',
      render: (text) => (text ? text.slice(0, 10) : ''),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handleEditAdmin(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDeleteAdmin(record)}>删除</Button>
        </div>
      ),
    },
  ];

  return (
    <div className="table-wrapped">
      <div className="table-top">
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <div className="search-wrapped">
            <Input
              value={adminAccount}
              onChange={e => setAdminAccount(e.target.value)}
              style={{ width: 300 }}
              size="large"
              placeholder="输入账号进行搜索"
              prefix={<SearchOutlined />}
              onPressEnter={searchAdmin}
              allowClear
              onClear={clearInput}
            />
          </div>
          <div className="button-wrapped">
            <Button type="primary" onClick={() => setCreateModalVisible(true)}>添加消息管理员</Button>
          </div>
        </div>
        <div className="table-content">
          <Table
            columns={columns}
            dataSource={tableData}
            pagination={false}
            loading={loading}
            rowKey="id"
          />
        </div>
      </div>
      <div style={{
        display: 'flex',
        justifyContent: 'flex-end',
        marginTop: 20,
      }}>
        <Pagination
          pageSize={10}
          current={paginationData.currentPage}
          total={adminTotal}
          showSizeChanger={false}
          onChange={handlePaginationChange}
          showQuickJumper
          pageSizeOptions={['10']}
        />
      </div>
      <CreateAdminDialog visible={createModalVisible} onClose={() => setCreateModalVisible(false)} onSuccess={() => fetchFirstPageList()} />
      <EditAdminDialog visible={editModalVisible} onClose={() => setEditModalVisible(false)} onSuccess={() => fetchFirstPageList()} adminId={adminId} />
    </div>
  );
};


export default AdminPage;
